package cn.tedu.kcircle.common.util;




import cn.tedu.kcircle.common.po.PageData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;

import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TransPage {
    public static <T> PageData<T> list2Page(List<T> list) {
        Page<T> page=(Page<T>)list;
        PageInfo<T> tPageInfo = new PageInfo<T>(page);
        PageData<T> tPageData = new PageData<T>()
                .setList(tPageInfo.getList())
                .setPageNum(tPageInfo.getPageNum())
                .setPageSize(tPageInfo.getPageSize())
                .setTotal(tPageInfo.getTotal())
                .setMaxPage(tPageInfo.getPages());
        return tPageData;
    }
    public static <T> PageData<T> search2Page(SearchPage<T> searchPage) {
        SearchHits<T> searchHits = searchPage.getSearchHits();
        Map<String, PropertyDescriptor> descriptorMap = new HashMap<>();
        List<T> list = searchHits.stream().map(item -> {
            T content = item.getContent();
            Map<String, List<String>> highlightFields = item.getHighlightFields();
            Class<?> aClass = content.getClass();
            highlightFields.forEach((k, v) -> {
                PropertyDescriptor propertyDescriptor;
                try {
                    if (descriptorMap.containsKey(k)) {
                        propertyDescriptor = descriptorMap.get(k);
                    } else {
                        propertyDescriptor = new PropertyDescriptor(k, aClass);
                        descriptorMap.put(k, propertyDescriptor);
                    }
                    if(!v.isEmpty()){
                        propertyDescriptor.getWriteMethod().invoke(content, v.get(0));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            return content;
        }).toList();

        return new PageData<T>()
                .setPageNum(searchPage.getNumber() + 1)
                .setPageSize(searchPage.getSize())
                .setTotal(searchPage.getTotalElements())
                .setMaxPage(searchPage.getTotalPages())
                .setList(list);
    }

}
